package com.ludomancy.sos64.components;

import java.awt.Graphics;
import java.awt.Point;

import com.ludomancy.gamelib.ImageAnimation;
import com.ludomancy.gamelib.ImageStrip;
import com.ludomancy.gamelib.Randomizer;
import com.ludomancy.gamelib.ResourceManager;
import com.ludomancy.gamelib.Sound;
import com.ludomancy.sos64.Component;
import com.ludomancy.sos64.Game;

public class Turbine extends Component
{
	private ImageAnimation blade;
	private ImageAnimation spark;
	
	public boolean generating = false;
	private boolean fixed = false;
	
	public Turbine(Point pos)
	{
		this(pos, false);
	}
	
	public Turbine(Point pos, boolean fixed)
	{
		super(pos.x,pos.y);
		this.fixed = fixed;
		if(blade == null)
		{
			blade = new ImageAnimation(new ImageStrip(ResourceManager.getImage("blade.png"), 15, 34), 2);
			spark = new ImageAnimation(new ImageStrip(ResourceManager.getImage("spark.png"), 9, 13), 2);
			spark.looping = true;
		}
		blade.looping = true;
	}
	
	public boolean isMadeOfMetal()
	{
		return true;
	}
	
	public boolean canMove()
	{
		return !fixed;
	}
	
	public Point getSize()
	{
		return new Point(15,34);
	}

	public void paint(Graphics g, int px, int py)
	{
//		if(generating)
//		{
//			g.translate(0, 4);
//			Utils.pushClipStack(g);
//			g.setClip(px,py,getSize().x, getSize().y - 4);
//		}
		blade.paintCurrentFrame(g, px, py);
//		if(generating)
//		{
//			g.translate(0, -4);
//			Utils.popClipStack(g);
//		}
		if(generating)
		{
			spark.paintCurrentFrame(g, Randomizer.getRandom(px, px + getSize().x - spark.strip.frameWidth), Randomizer.getRandom(py, py + getSize().y - spark.strip.frameHeight));
		}
	}

	public void update()
	{
		blade.update();
		spark.update();
		Point tile = Game.game.tileFor(getHotspot());
		if(Game.game.terrain.isWater(tile.x, tile.y) && Game.game.dam.isConsumed())
		{
			if(generating == false)
			{
				Sound.play("electric.wav");
			}
			generating = true;
			blade.play();
			spark.play();
		}
		else
		{
			generating = false;
			blade.stop();
			blade.rewind();
			spark.stop();
		}
	}
}
